$(document).ready(function() {
	//preload images
	for(i=1;i<=MAX_IMAGES;i++) {
	  	img = new Image();
	  	img.src = 'images/'+i+'.JPG';	      		
	}
	init();

  update();
  $('body').bind('click',function(e){
	var pos = getPosition(e);
  	var num = random(1,MAX_IMAGES);
  	filename = num+".JPG";

	var poster = new Object();
	poster.x = pos.x;
	poster.y = pos.y;
	poster.fileName = filename;
	poster.team = team;
	$.ajax({
		type: "POST",
		url: "Ajax/ajax_handler.php",
		data: "fct=addPoster&x="+poster.x+"&y="+poster.y+"&team="+poster.team+"&fileName="+poster.fileName,
		success: function(msg){
			displayImage(poster);
			window.location.reload()
		}
	});
  });
});

function loadTeam(id_team) {
	team = id_team;
	
}

function init() {
	var canvas = document.getElementById('main');  
	var x = 0;
	var y = 0;
	canvas.height = 500;
	canvas.width = 500;
}

function checkout() {
	$.ajax({
		type: "POST",
		url: "Ajax/ajax_handler.php",
		data: "fct=update&init=1",
		success: function(msg){
			if(msg != "") {
				data = eval("(" + msg + ")");	
				displayImages(data);
			}
		}
	});
}
function update() {
	$.ajax({
		type: "POST",
		url: "Ajax/ajax_handler.php",
		data: "fct=update",
		success: function(msg){
			if(msg != "" && msg != "null") {
				data = eval("(" + msg + ")");	
				displayImages(data);			
			}
		}
	});
}

function displayImages(data) {
	if (null != data) {
		for(i = 0; i < data.length; i++) {
			displayImage(data[i]);
		}
	}
}

function displayImage(poster) {
	if(poster.fileName != "") {
		var img = new Image();
		img.src = IMAGE_PATH+poster.fileName;
		var ctx = document.getElementById('main').getContext('2d'); 
	  	ctx.drawImage(img, poster.x-(IMAGE_SIZE/2), poster.y-(IMAGE_SIZE/2));		
	}
}